package com.example.business.config;

import com.example.business.filter.JwtAuthenticationFilter;
import com.example.business.handler.JwtLoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;

/**
 * @Description 请描述下该类是做什么的
 * @Author <a href="mailto:yuanlx@smartdot.com.cn">袁凌霄</a>
 * @Date 2021/9/13  23:09
 * @Verson 1.0
 **/

//由于Spring boot starter自动装配机制,这里无需使用@EnableWebSecurity
//@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 方法授权
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
// 配置用户时使用加密后的密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        String encodedPassword = passwordEncoder().encode("123456"); // 加密密码
//        auth.inMemoryAuthentication()
//                .withUser("admin")
//                .password(encodedPassword) // 存储加密后的密码
//                .roles("USER");

        auth.userDetailsService(userDetailsService);
    }
    // 密码编码器,不加密
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();// BCryptPasswordEncoder加密
    }

    // web url 拦截规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // 1. 放行跨域预检请求（OPTIONS方法），必须添加！
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                // 2. 放行登录相关接口/页面
                .antMatchers("/login.html", "/index.html", "/login", "/login/**").permitAll()
                // 其他请求需要认证
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html") // 自定义登录页
                .loginProcessingUrl("/login") // 登录表单提交接口
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(new JwtLoginSuccessHandler())
                .failureHandler((req, res, e) -> {
                    res.setContentType("application/json;charset=UTF-8");
                    res.getWriter().write("{\"code\":401,\"msg\":\"用户名或密码错误\"}");
                })
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态（禁用Session）
                .and()
                // 3. 添加Token验证过滤器（保持不变）
                .addFilterBefore(new JwtAuthenticationFilter(userDetailsService), UsernamePasswordAuthenticationFilter.class)
                // 4. 启用CORS（关键！与CorsConfig配合生效）
                .cors()
                .and()
                // 禁用CSRF（保持不变，前后端分离场景常用）
                .csrf().disable();
    }
}
